<?php

function print_debug($variable)
{
    echo "<pre>";
    var_dump($variable);
    echo "</pre>";
}


include_once "book.php";

$importDir = "./import/" ;


$host="localhost";
$port=3306;
$socket="";
$user="root";
$password="";
$dbname="library";

$connection = new mysqli($host, $user, $password, $dbname, $port, $socket)
or die ('Could not connect to the database server' . mysqli_connect_error());

$connection->set_charset("utf8");








$currentDirContent = scandir($importDir);

$droppedFilesCounter = 0;

for ($filesCounter=0; $filesCounter <= sizeof($currentDirContent); $filesCounter++)
{
    if (strcmp(mb_substr($currentDirContent[$filesCounter],-3,3),".gz")!== 0)
    {
        unset($currentDirContent[$filesCounter]);
        $droppedFilesCounter++;
    }

}
// need +1 cause starts from 0 and not 1
$books2import = $filesCounter-$droppedFilesCounter+1 ;

// FOREACH for GUNZIPed files

$query= array();
$counter = 89 ;
foreach ($currentDirContent as $currentBookFile)
{

   $tmp = new Book;
   $tmp->readDataFromFile($importDir.$currentBookFile) ;


   /*
		// extract and copy cover picture to ./cover dir
		 $currentCoverFileHandle = fopen("./covers/".$tmp->pureFileName."_cover.jpg", "w+");
		 fwrite($currentCoverFileHandle, base64_decode($tmp->binary));
		// echo "./covers/".$tmp->pureFileName."_cover.jpg " . round((memory_get_peak_usage()/1024)/1024) . "Mb". PHP_EOL;
		 fclose ($currentCoverFileHandle) ;
   */


   	$query[] = '("'.$counter.'", "'.$connection->real_escape_string($tmp->annotation).'")';

   	$counter++;

  unset($tmp);
}

$connection->query('INSERT INTO `library`.`annotation` (`bookid`, `annotation`) VALUES '.implode(',', $query));


$connection->close();
echo "all done";



?>